package com.person.ntv.controller.sys;

import java.io.File;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import net.sf.json.JSONArray;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.person.Constants;
import com.person.common.PageParams;
import com.person.easyui.EasyUItools;
import com.person.easyui.TreeNode;
import com.person.easyui.TreeNodeRule;
import com.person.exception.ServiceException;
import com.person.layui.Menu;
import com.person.ntv.entity.sys.SysResource;
import com.person.ntv.entity.sys.SysUser;
import com.person.ntv.service.sys.CommonService;
import com.person.ntv.service.sys.SysResourceService;

@Controller
@RequestMapping("/system/sysResource")
public class SysResourceController {
	@Autowired
	private SysResourceService sysResourceService;
	@Autowired
	private CommonService commonService;
	
	@RequestMapping("/menuTree")
	@ResponseBody
	public List<Menu> getMenuTree(Map<String,String> params,HttpServletRequest request){
		SysUser sysUser=(SysUser)request.getSession().getAttribute(Constants.CURRENT_USER);
		params.put("resType","1");
		params.put("userId",sysUser.getId().toString());
		params.put("parentIds", request.getParameter("parentId"));
	    List<Map<String,Object>> list = sysResourceService.getMenuTree(params);
	    List<Menu> result=new ArrayList<Menu>();
	    if(list!=null&&list.size()>0){
	    	result=Menu.listToMenus(request.getParameter("parentId"),list);
		}
		return result;
	}
	 
	private List<Map<String,Object>> menuList(List<Map<String,Object>> list){
		List<Map<String,Object>> result=new ArrayList<Map<String,Object>>();
		Map<String,Object> rMap=new HashMap<String,Object>();
		
		return result;
	}
	@RequestMapping("/listPage")
	public String  getResourceListPage(Map<String,String> params,ModelMap mv){
		initCode(mv);
		return "/system/resource/menuList";
	}
	
	@RequestMapping("/listPage2")
	public String  getResourceListPage2(Map<String,String> params,ModelMap mv){
		initCode(mv);
		return "/system/resource/pageList";
	}
	
	@RequestMapping("/resourceList")
	@ResponseBody
	public Map<String,Object> getResourceList(PageParams myPage){
		List<Map<String,Object>> dataList=sysResourceService.getMenuTree(myPage.getParams());
		for(int i=0;i<dataList.size();i++){
			Object pId=dataList.get(i).get("_parentId");
			boolean flag=true;
			for(int k=0;k<dataList.size();k++){
				 if(String.valueOf(dataList.get(k).get("id")).equals(String.valueOf(pId)))
					  flag=false;
			}
			if(flag)
				dataList.get(i).put("_parentId", null);
		}
        Map<String,Object> map=new HashMap<String,Object>();
        map.put("total",dataList.size());
        map.put("rows",dataList);
		return map;
	}
	
	@RequestMapping("/addPage")
	public String  addResourcePage(String pId,ModelMap mv){
		initCode(mv);
		mv.addAttribute("pId", pId);
		return "/system/resource/menuAdd";
	}
	
	@RequestMapping("/editPage")
	public String  editResourcePage(String id,ModelMap mv){
		try {
		initCode(mv);
	    SysResource menu = sysResourceService.selectByPrimaryKey(new BigDecimal(id));
	    mv.addAttribute("menu",menu);
		} catch (ServiceException e) {
			mv.addAttribute("error", "1");
			mv.addAttribute("msg",e.getMessage()+"查询出错！");
		}
		return "/system/resource/menuEdit";
	}
	
	@RequestMapping("/addPage2")
	public String  addResourcePage2(String pId,ModelMap mv){
		mv.addAttribute("pId", pId);
		return "/system/resource/pageAdd";
	}
	
	@RequestMapping("/editPage2")
	public String  editResourcePage2(String id,ModelMap mv){
		try {
	    SysResource menu = sysResourceService.selectByPrimaryKey(new BigDecimal(id));
	    mv.addAttribute("menu",menu);
		} catch (ServiceException e) {
			mv.addAttribute("error", "1");
			mv.addAttribute("msg",e.getMessage()+"查询出错！");
		}
		return "/system/resource/pageEdit";
	}
	
	@RequestMapping("/addResource")
	public String  addResource(ModelMap mv,SysResource sysResource){
		try {
			BigDecimal parentId = sysResource.getParentId();
			sysResource.setParentIds(sysResourceService.selectByPrimaryKey(parentId).getParentIds()+parentId+"/");
			sysResourceService.insertSelective(sysResource);
			//InitApplication.privageList=sysResourceService.selectAll();
			mv.addAttribute("error", "0");
			mv.addAttribute("msg","保存成功！");
		} catch (ServiceException e) {
			mv.addAttribute("error", "1");
			mv.addAttribute("msg",e.getMessage()+"保存失败！");
		}
		return "/system/resource/menuAdd";
	}
	
	@RequestMapping("/editResource")
	public String  editResource(ModelMap mv,SysResource sysResource){
		try {
			sysResourceService.updateByPrimaryKeySelective(sysResource);
			//InitApplication.privageList=sysResourceService.selectAll();
			mv.addAttribute("error", "0");
			mv.addAttribute("msg","保存成功！");
		} catch (ServiceException e) {
			mv.addAttribute("error", "1");
			mv.addAttribute("msg",e.getMessage()+"保存失败！");
		}
		return "/system/resource/menuEdit";
	}
	
	@RequestMapping("/delResource")
	@ResponseBody
	public Map<String,Object>  delResource(BigDecimal[]ids,HttpServletRequest request){
		Map<String,Object> map=new HashMap<String,Object>();
		try {
			sysResourceService.deleteByPrimaryKeys(ids); 
			//InitApplication.privageList=sysResourceService.selectAll();
			map.put("error", "0");
			map.put("msg","删除成功！");
		} catch (ServiceException e) {
			map.put("error", "1");
			map.put("msg",e.getMessage()+"删除失败！");
		}
		return map;
	}
	
	@RequestMapping("/detailPage")
	public String  detailResourcePage(String id,ModelMap mv){
		try {
	    SysResource menu = sysResourceService.selectByPrimaryKey(new BigDecimal(id));
	    mv.addAttribute("menu",menu);
		} catch (ServiceException e) {
			mv.addAttribute("error", "1");
			mv.addAttribute("msg",e.getMessage()+"查询出错！");
		}
		return "/system/resource/menuDetail";
	}
	
	@RequestMapping("/detailPage2")
	public String  detailResourcePage2(String id,ModelMap mv){
		try {
	    SysResource menu = sysResourceService.selectByPrimaryKey(new BigDecimal(id));
	    mv.addAttribute("menu",menu);
		} catch (ServiceException e) {
			mv.addAttribute("error", "1");
			mv.addAttribute("msg",e.getMessage()+"查询出错！");
		}
		return "/system/resource/pageDetail";
	}
	
	@RequestMapping("/validateResName")
	@ResponseBody
	public boolean validateResName(SysResource sysResource){
		try {
			if(sysResource.getResName()==null)sysResource.setResName("");
			int cnt=sysResourceService.validateResName(sysResource.getResName(),sysResource.getId()==null?null:String.valueOf(sysResource.getId()));
			if(cnt==0)
			return true;
		} catch (ServiceException e) {
           e.printStackTrace();
		}
		return false;
	}
	
	@RequestMapping("/validateResCode")
	@ResponseBody
	public boolean validateResCode(SysResource sysResource){
		try {
			if(sysResource.getResCode()==null)sysResource.setResCode("");
			int cnt=sysResourceService.validateResCode(sysResource.getResCode(),sysResource.getId()==null?null:String.valueOf(sysResource.getId())); 
			if(cnt==0)
			return true;
		} catch (ServiceException e) {
			e.printStackTrace();
		}
		return false;
		}
	      
	@RequestMapping("/icons")
	@ResponseBody
	public List<Map<String,Object>> getIcons(HttpServletRequest request,String curIcon){
		try {
		    String path=request.getSession().getServletContext().getRealPath(File.separator)+"easyui"+File.separator+"themes"+File.separator+"icons";
		    File dFile=new File(path);
		    File[]files=dFile.listFiles();
		    List<Map<String,Object>>list=new ArrayList<Map<String,Object>>();
		    Map<String,Object> def=new HashMap<String,Object>();
		     def.put("id","");
		     def.put("text","请选择");
		     def.put("icon","easyui"+File.separator+"themes"+File.separator+"icons"+File.separator+"blank.gif");
		     if(curIcon==null||curIcon.trim().equals(""))
		    	 def.put("selected",true);
		     list.add(def);
		    for(File file:files){
		    	Map<String,Object> map=new HashMap<String,Object>();
		    	String id="icon-"+file.getName().substring(0,file.getName().lastIndexOf(".")).replace("_","-");
		    	map.put("id",id);
		    	map.put("text",id);
		    	map.put("icon","easyui"+File.separator+"themes"+File.separator+"icons"+File.separator+file.getName());
		    	if(curIcon!=null&&curIcon.equals(id))
		    		map.put("selected",true);
		    	list.add(map);
		    }
		    return list;
		} catch (ServiceException e) {
			e.printStackTrace();
		}
		return null;
	 }
	
	private void initCode(ModelMap mv){
		mv.addAttribute("MenuOpenType",JSONArray.fromObject(commonService.getCodeList("MenuOpenType",true)).toString());
	}
}
